const { adminInfo } = require('../config/config'),
      { addAdminData, loginCheckInfo } = require('../services/AdminService'),
      { makeCrypto, trimSpace, returnInfo } = require('../libs/utils'),
      errorInfo = require('../config/error_config'),
      { LOGIN } = errorInfo; //登录信息配置


class AdminController {

  /* 创建用户*/
  async createAdmin (ctx, next) {
    //加密
    adminInfo.password = makeCrypto(adminInfo.password);

    const result = await addAdminData(adminInfo);
    if(result) {
      console.log(0);
    }else {
      console.log(1);
    }
  }

  //登录状态验证 判断登录状态  
  async loginCheck (ctx, next) {
    //检查两个条件是否满足，满足才算登录状态
    //用户登录时携带了cookie，服务器管理中间件会自动识别匹配
    //匹配成功的时候，会得到ctx.session.userInfo的信息
    if(ctx.session && ctx.session.userInfo) {
      //登录状态
      ctx.body = returnInfo(LOGIN.LOGIN_STATUS);
      return;
    }

    ctx.body = returnInfo(LOGIN.NOT_LOGIN_STATUS);
  }

  /* 登录接口*/
  async loginAction (ctx, next) {
    const { username, password } = ctx.request.body;

    if (!username || !password ) {
      ctx.body = returnInfo (LOGIN.INVALID_OPERATION);
      return;
    }

    if ( trimSpace(username).length <= 0 ) {
      ctx.body = returnInfo(LOGIN.INVALID_USERNAME_LENGTH);
      return;
    }

    if(trimSpace(password).length <= 0 ) {
      ctx.body = returnInfo(LOGIN.INVALID_PASSWORD_LENGTH);
      return;
    }

    const userInfo = {
      username: trimSpace(username),
      password: makeCrypto( trimSpace(password) )
    }

    const result = await loginCheckInfo(userInfo);

    if( result === 10003) {
      ctx.body = returnInfo(LOGIN.USERNAME_NOT_EXIST);
      return;
    }

    if( result === 10004) {
      ctx.body = returnInfo(LOGIN.PASSWORD_ERROR);
      return;
    }

  
    //这里设置session的东西
    if(!ctx.session.userInfo) {
      //访问userInfo是否存在，不存在就是undefined，此时设置
      ctx.session.userInfo = result;
    }

    ctx.body = returnInfo(LOGIN.SUCCESS, ctx.session.userInfo); //成功返uid和username数据 传入
  }

  /* 退出登录*/
  async logoutAction (ctx, next) {
    delete ctx.session.userInfo;
    ctx.body = returnInfo(LOGIN.LOGOUT_SUCCESS);
  }
}

module.exports = new AdminController();